<template>
  <div class="min-h-screen bg-gray-50 p-4 md:p-6 lg:p-8">
    <div class="max-w-4xl mx-auto">
      <a-card title="倒计时器" class="mb-4">
        <div class="space-y-6">
          <!-- 倒计时设置 -->
          <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">
                倒计时类型
              </label>
              <a-radio-group v-model:value="countdownType" @change="resetCountdown">
                <a-radio value="timer">计时器</a-radio>
                <a-radio value="date">日期</a-radio>
              </a-radio-group>
            </div>

            <!-- 计时器设置 -->
            <div v-if="countdownType === 'timer'" class="space-y-4">
              <div class="grid grid-cols-3 gap-2">
                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-1">时</label>
                  <a-input-number
                    v-model:value="hours"
                    :min="0"
                    :max="99"
                    style="width: 100%"
                  />
                </div>
                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-1">分</label>
                  <a-input-number
                    v-model:value="minutes"
                    :min="0"
                    :max="59"
                    style="width: 100%"
                  />
                </div>
                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-1">秒</label>
                  <a-input-number
                    v-model:value="seconds"
                    :min="0"
                    :max="59"
                    style="width: 100%"
                  />
                </div>
              </div>
            </div>

            <!-- 日期设置 -->
            <div v-else class="space-y-4">
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">
                  目标日期和时间
                </label>
                <a-date-picker
                  v-model:value="targetDate"
                  :show-time="true"
                  style="width: 100%"
                />
              </div>
            </div>
          </div>

          <!-- 倒计时显示 -->
          <div class="text-center py-8 bg-gray-50 rounded-lg">
            <div class="text-5xl font-bold font-mono">
              {{ formatTime(remainingTime) }}
            </div>
            <div v-if="countdownType === 'date' && targetDate" class="mt-2 text-gray-500">
              距离 {{ formatDate(targetDate) }}
            </div>
          </div>

          <!-- 控制按钮 -->
          <div class="flex justify-center space-x-4">
            <a-button
              type="primary"
              :disabled="!canStart"
              @click="toggleCountdown"
            >
              {{ isRunning ? '暂停' : '开始' }}
            </a-button>
            <a-button @click="resetCountdown">
              重置
            </a-button>
          </div>

          <!-- 预设时间 -->
          <div>
            <h4 class="text-sm font-medium text-gray-700 mb-2">快捷设置</h4>
            <div class="grid grid-cols-2 md:grid-cols-4 gap-2">
              <a-button
                v-for="preset in presets"
                :key="preset.value"
                size="small"
                @click="applyPreset(preset.value)"
              >
                {{ preset.label }}
              </a-button>
            </div>
          </div>
        </div>
      </a-card>

      <!-- 使用说明 -->
      <a-card title="使用说明" class="mb-4">
        <ol class="list-decimal list-inside space-y-2 text-gray-600">
          <li>选择倒计时类型：计时器或目标日期</li>
          <li>设置时间或选择日期</li>
          <li>点击开始按钮启动倒计时</li>
          <li>可以随时暂停或重置</li>
          <li>时间到达时会有提示音</li>
        </ol>
      </a-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onUnmounted } from 'vue'
import { message } from 'ant-design-vue'
import dayjs, { Dayjs } from 'dayjs'

// 状态
const countdownType = ref<'timer' | 'date'>('timer')
const hours = ref(0)
const minutes = ref(0)
const seconds = ref(0)
const targetDate = ref<Dayjs>()
const remainingTime = ref(0)
const isRunning = ref(false)
let timer: number | null = null

// 预设时间（秒）
const presets = [
  { label: '5分钟', value: 300 },
  { label: '10分钟', value: 600 },
  { label: '15分钟', value: 900 },
  { label: '30分钟', value: 1800 },
  { label: '1小时', value: 3600 },
  { label: '2小时', value: 7200 },
  { label: '4小时', value: 14400 },
  { label: '8小时', value: 28800 }
]

// 计算是否可以开始
const canStart = computed(() => {
  if (countdownType.value === 'timer') {
    return hours.value > 0 || minutes.value > 0 || seconds.value > 0
  } else {
    return targetDate.value && targetDate.value.isAfter(dayjs())
  }
})

// 格式化时间显示
const formatTime = (seconds: number) => {
  const h = Math.floor(seconds / 3600)
  const m = Math.floor((seconds % 3600) / 60)
  const s = seconds % 60
  return `${h.toString().padStart(2, '0')}:${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`
}

// 格式化日期显示
const formatDate = (date: Dayjs) => {
  return date.format('YYYY年MM月DD日 HH:mm:ss')
}

// 更新剩余时间
const updateRemainingTime = () => {
  if (countdownType.value === 'timer') {
    if (remainingTime.value > 0) {
      remainingTime.value--
    } else {
      stopCountdown()
      playAlarm()
      message.success('时间到！')
    }
  } else if (targetDate.value) {
    const now = dayjs()
    const diff = targetDate.value.diff(now, 'second')
    if (diff > 0) {
      remainingTime.value = diff
    } else {
      stopCountdown()
      playAlarm()
      message.success('时间到！')
    }
  }
}

// 开始/暂停倒计时
const toggleCountdown = () => {
  if (isRunning.value) {
    stopCountdown()
  } else {
    startCountdown()
  }
}

// 开始倒计时
const startCountdown = () => {
  if (!canStart.value) return

  if (countdownType.value === 'timer' && !isRunning.value) {
    remainingTime.value = hours.value * 3600 + minutes.value * 60 + seconds.value
  }

  isRunning.value = true
  timer = window.setInterval(updateRemainingTime, 1000)
}

// 停止倒计时
const stopCountdown = () => {
  if (timer) {
    clearInterval(timer)
    timer = null
  }
  isRunning.value = false
}

// 重置倒计时
const resetCountdown = () => {
  stopCountdown()
  if (countdownType.value === 'timer') {
    remainingTime.value = hours.value * 3600 + minutes.value * 60 + seconds.value
  } else if (targetDate.value) {
    const diff = targetDate.value.diff(dayjs(), 'second')
    remainingTime.value = diff > 0 ? diff : 0
  } else {
    remainingTime.value = 0
  }
}

// 应用预设时间
const applyPreset = (value: number) => {
  countdownType.value = 'timer'
  hours.value = Math.floor(value / 3600)
  minutes.value = Math.floor((value % 3600) / 60)
  seconds.value = value % 60
  resetCountdown()
}

// 播放提示音
const playAlarm = () => {
  const audio = new Audio('/toolbox/alarm.mp3')
  audio.play().catch(() => {
    console.log('无法播放提示音')
  })
}

// 组件卸载时清理
onUnmounted(() => {
  stopCountdown()
})
</script> 